<?php
/**
 * Created by XM·Tan.
 * Motto: Who shuts love out, in turn shall be shut out from love.
 * Date: 2021/3/23 1:27
 */

namespace app\admin\controller;

use app\admin\business\AdminUser as AdminUserBusiness;
use app\admin\validate\AdminUser as AdminUserValidate;
use app\admin\business\AdminRole as AdminRoleBus;
use app\common\lib\ArrayLib;
use app\common\lib\Password;
use app\common\lib\Show;
use think\Exception;
use think\facade\View;

class Admin extends AdminBase {

    public $business = null;
    public function __construct() {
        $this->business = new AdminUserBusiness();
    }

    public function index() {
        return View::fetch();
    }

    public function getLists() {
        $data = [];
        $limit = input('param.limit', 10, 'intval');
        $username = input('param.username', '', 'trim');
        $time = input('param.time', '', 'trim');

        if (!empty($username)) {
            $data['username'] = $username;
        }

        if (!empty($time)) {
            $data['last_login_time'] = explode(" - ", $time);
        }

        $result = (new AdminUserBusiness())->getLists($data, $limit);
        return Show::show_lay_table(config('layui.success'), '', $result['total'], $result['data']);
    }

    // 添加管理员
    public function add() {
        if(request()->isPost()){
            $data = input('param.');
            // 使用 validate 验证机制验证参数
            $validate = new AdminUserValidate();
            if (!$validate->scene('insert')->check($data)) {
                return Show::error($validate->getError());
            }

            // 执行 business 操作
            $res = (new AdminUserBusiness())->insertData($data);
            if (!$res) {
                return Show::error('添加管理员失败');
            }
            return Show::success('添加管理员成功');
        } else {
            $result = (new AdminRoleBus())->getRoleLists();
            return View::fetch('', [
                'roleList' => json_encode($result, true)
            ]);
        }
    }

    // 编辑管理员
    public function edit() {
        if(request()->isPost()){
            $data = input('param.');
            // 使用 validate 验证机制验证参数
            $validate = new AdminUserValidate();
            if (!$validate->scene('update')->check($data)) {
                return Show::error($validate->getError());
            }

            // 执行 business 操作
            $res = (new AdminUserBusiness())->updateData($data);
            if (!$res) {
                return Show::error('更新管理员失败');
            }
            return Show::success('更新管理员成功');

        } else {
            $result = (new AdminRoleBus())->getRoleLists();

            $id = input('param.id', 0, 'intval');
            if ($id == 0) {
                throw new Exception('请求不合法');
            }
            $info = (new AdminUserBusiness())->getById($id);
            $result = ArrayLib::setAuthChecked($result, $info['role_id'], 'selected');
            return View::fetch('', [
                'roleList' => json_encode($result, true),
                'info' => $info
            ]);
        }
    }

    // 基本资料
    public function setting() {
        if(request()->isPost()){
            $data = input('param.');
            // 使用 validate 验证机制验证参数
            $validate = new AdminUserValidate();
            if (!$validate->scene('setting')->check($data)) {
                return Show::error($validate->getError());
            }

            // 执行 business 操作
            $res = (new AdminUserBusiness())->updateData($data);
            if (!$res) {
                return Show::error('修改基本失败');
            }
            return Show::success('修改基本成功');
        } else {
            $id = input('param.id', 0, 'intval');
            if ($id == 0) {
                throw new Exception('请求不合法');
            }
            $info = (new AdminUserBusiness())->getById($id);
            return View::fetch('', [
                'info' => $info
            ]);
        }
    }

    // 修改密码
    public function password() {
        if(request()->isPost()){
            $data = input('param.');
            // 使用 validate 验证机制验证参数
            $validate = new AdminUserValidate();
            if (!$validate->scene('password')->check($data)) {
                return Show::error($validate->getError());
            }
            if ($data['password'] != $data['again_password']) {
                return Show::error('新密码和确认密码不一致');
            }

            $info = (new AdminUserBusiness())->getById($data['id']);
            if ($info['password'] != Password::encrypt_password($data['old_password'], $info['encrypt'])) {
                return Show::error('旧密码错误');
            }

            // 组装更新数据
            $upDate = [
                'id' => $data['id'],
                'password' => $data['password']
            ];

            // 执行 business 操作
            $res = (new AdminUserBusiness())->updateData($upDate);
            if (!$res) {
                return Show::error('修改密码失败');
            }
            session(config('admin.session_admin'), null);
            return Show::success('修改密码成功');
        } else {
            $id = input('param.id', 0, 'intval');
            if ($id == 0) {
                throw new Exception('请求不合法');
            }
            $info = (new AdminUserBusiness())->getById($id);
            return View::fetch('', [
                'info' => $info
            ]);
        }
    }

}